/* 
 * UCLA CS 111 - Fall 2007 - Lab 1
 * Skeleton code for Lab 1 - Shell processing
 * This file contains skeleton code for executing commands parsed in part A.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include "cmdline.h"
#include "ospsh.h"


#include <sys/types.h>
#include <dirent.h>



/*

#include <readline/readline.h>
#include <readline/history.h>

*/


/*
   Part of this project uses code from the GNU Readline Library. Here is the
   legal copyright information:

  Copyright (C) 1987-2009 Free Software Foundation, Inc.

   This file is part of the GNU Readline Library (Readline), a library for
   reading lines of text with interactive input and history editing.

   Readline is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Readline is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Readline.  If not, see <http://www.gnu.org/licenses/>.
*/


#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <sys/types.h>
#ifdef HAVE_SYS_FILE_H
#  include <sys/file.h>
#endif
#include <sys/stat.h>

#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

#if defined (HAVE_STRING_H)
#  include <string.h>
#else /* !HAVE_STRING_H */
#  include <strings.h>
#endif /* !HAVE_STRING_H */

#ifdef HAVE_STDLIB_H
#  include <stdlib.h>
#endif

#include <time.h>

#ifdef READLINE_LIBRARY
#  include "readline.h"
#  include "history.h"
#else
#  include <readline/readline.h>
#  include <readline/history.h>
#endif




char *
dupstr (s)
     char *s;
{
  char *r;

  r = malloc (strlen (s) + 1);
  strcpy (r, s);
  return (r);
}


/* EXERCISE: Make sure you free memory used by the command_t structures
 * when it is no longer needed.
 * EXERCISE:  Make sure you clean up ALL zombie processes, including those
 * that ran in the background!
 * There are several ways to do this, and several places to put the code.
 * Check out the SIGCHLD signal and the waitpid() system call for hints.
 * HINT:
 *   You DO NOT need to clean up zombies as soon as they are created.
 *   It is OK to clean up zombies as little as once per command.
 *   That is, it is OK if a zombie hangs around until the next time the user
 *   types a command.  But it is NOT OK for zombies to hang around forever.
 */



char** command_list;

#define MAX_FILE_LENGTH 255

int files_in_directory (char* path)
{

  struct dirent *ent;

  DIR* num_files; 
  int file_count;

  file_count = 0;
  
  num_files = opendir(path);

  if (num_files != NULL) {
    
    while(( ent = readdir(num_files)) != NULL) file_count++;
  }


  //closedir(num_files);
 
   
  return file_count;
}


void add_files_to_command(char* path, char** where_to_start)
{
  	DIR *dir;

	int file_count;
	
	struct dirent *ent;

	// TODO: Need to change this to a path based off the PATH variable

	dir = opendir (path);

	if (dir != NULL) {
	  
	  file_count = files_in_directory(path);


	 	  
	  int i;
	  i = 0;

	  /* print all the files and directories within directory */
	  for (i=0; i < file_count && (ent = readdir (dir)) != NULL; i++) {
	    
	 
	    where_to_start[i] = ent->d_name;

	  }
	  closedir (dir);
	} else {
	  /* could not open directory */
	  perror ("");
	  //return EXIT_FAILURE;
	}


}

void init_commands ()
{

  char* path = "/usr/bin";

  int file_count;
  int total_count;

  char** listOfPaths;

  int num_paths;

  // Call Sam's function here
  num_paths = delimit(path, &listOfPaths);


  int i;
  for(i = 0; i < num_paths; i++)
    {
      total_count += files_in_directory(listOfPaths[i]);

    }

  

  // file_count = files_in_directory(path);

   // alloc the array of commands.
  command_list = malloc(total_count * sizeof(char*));

  int j;

  for(j = 0; j < num_paths; j++)
    add_files_to_command(listOfPaths[j], command_list);



}


/* 
 * Main function for shell.
 */


void initialize_readline ();

int
main(int argc, char *argv[])
{
	int quiet = 0;
	char input[BUFSIZ];
	int r = 0;
	
	char* input_ptr;

	// Check for '-q' option: be quiet -- print no prompts
	if (argc > 1 && strcmp(argv[1], "-q") == 0)
		quiet = 1;
	
	initialize_readline();

		
	init_commands();


	
	while (!feof(stdin)) {
		parsestate_t parsestate;
		command_t *cmdlist;
		// Print the prompt
		if (!quiet) {
		  //	printf("cs111_fall07$ ");
		  // fflush(stdout);
		  input_ptr = readline("cs111_fall07$ ");
		}

		/*
		// Read a string, checking for error or EOF
		if (fgets(input, BUFSIZ, stdin) == NULL) {
			if (ferror(stdin))
				// This function prints a description of the
				// error, preceded by 'cs111_fall07: '.
				perror("cs111_fall07");
			break;
			}*/

		

		
		// build the command list
		parse_init(&parsestate, input_ptr);

		cmdlist = command_line_parse(&parsestate, 0);
		if (!cmdlist) {
			printf("Syntax error\n");
			continue;
		}

       



		// print the command list
		if (!quiet) {
			command_print(cmdlist, 0);
			// why do we need to do this?
			fflush(stdout);
		}

		// and run it!
		if (cmdlist)
			command_line_exec(cmdlist);

	}

	free(input_ptr);
	free(command_list);

	return 0;
}



/* **************************************************************** */
/*                                                                  */
/*                  Interface to Readline Completion                */
/*                                                                  */
/* **************************************************************** */

char *command_generator PARAMS((const char *, int));
char **fileman_completion PARAMS((const char *, int, int));

/* FROM READLINE LIBRARY: Tell the GNU Readline library how to complete.  We want to try to complete
   on command names if this is the first word in the line, or on filenames
   if not. */
void initialize_readline ()
{
  /* Tell the completer that we want a crack first. */
  rl_attempted_completion_function = fileman_completion;
}


/* FROM READLINE LIBRARY:  Attempt to complete on the contents of TEXT.  START and END bound the
   region of rl_line_buffer that contains the word to complete.  TEXT is
   the word to complete.  We can use the entire contents of rl_line_buffer
   in case we want to do some simple parsing.  Return the array of matches,
   or NULL if there aren't any. */
char **
fileman_completion (text, start, end)
     const char *text;
     int start, end;
{
  char **matches;

  matches = (char **)NULL;

  /* If this word is at the start of the line, then it is a command
     to complete.  Otherwise it is the name of a file in the current
     directory. */
  if (start == 0)
    matches = rl_completion_matches (text, command_generator);

  return (matches);
}

/* Generator function for command completion.  STATE lets us know whether
   to start from scratch; without any state (i.e. STATE == 0), then we
   start at the top of the list. */
char *
command_generator (text, state)
     const char *text;
     int state;
{
  static int list_index, len;
  char *name;

  /* If this is a new word to complete, initialize now.  This includes
     saving the length of TEXT for efficiency, and initializing the index
     variable to 0. */
  if (!state)
    {
      list_index = 0;
      len = strlen (text);
    }

  
  /* Return the next name which partially matches from the command list. */
  while ((name = command_list[list_index]) != NULL)
    {
      list_index++;

      if (strncmp (name, text, len) == 0)
	

        return dupstr(name);
    }

   /*  If no names matched, then return NULL. */
  return ((char *)NULL);
}
